from flask import request, make_response
import redis

from utils import utils

class AdminPower:
    @staticmethod
    def update_power_state():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)

        data = request.get_json()
        station_id = data['S_id']
        power_status = data['status']
        if type(power_status) is str:
            power_status = int(power_status)
        db.hset(station_id, 'is_on', power_status)

        return make_response({"ok": True})

    @staticmethod
    def station_failure():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)

        data = request.get_json()
        station_id = data['S_id']
        db.hset(station_id, 'is_serve', -1)

        mode = db.hget(station_id, 'type')
        users = db.zrange(station_id + "_QUEUE", 0, -1)
        db.zrem(mode + "_STATION", station_id)

        if users:
            user_id = users[0]
            if db.exists(station_id + ":" + user_id):
                ttl = float(db.ttl(station_id + ":" + user_id))
                order_id = db.hget(user_id, "order")
                time_rate = float(db.get("TIME_RATE"))
                charge_time = ttl * time_rate
                db.hset(order_id, "charge_time", charge_time)

        for user in users:
            user_time = float(db.zscore(station_id + "_QUEUE", user))
            db.zrem(station_id + "_QUEUE", user)
            db.hset(user, "where", "wait")
            db.zadd(mode + "_QUEUE", {user: user_time})
        return make_response({"ok": True})
        pass

    @staticmethod
    def station_recovery():
        db = redis.Redis(host="localhost", port=6379, decode_responses=True)

        data = request.get_json()
        station_id = data['S_id']
        db.hset(station_id, 'is_serve', 0)

        mode = db.hget(station_id, 'type')
        db.zadd(mode + "_STATION", {station_id: utils.get_system_time()})

        # stations = db.smembers("station_list")
        # for station_id in stations:
        #     users = db.zrange(station_id + "_QUEUE", 0, -1)
        #     if users:
        #         users.pop(0)
        #     for user in users:
        #         user_time = float(db.zscore(station_id + "_QUEUE", user))
        #         db.zrem(station_id + "_QUEUE", user)
        #         db.hset(user, "where", "wait")
        #         db.zadd(mode + "_QUEUE", {user: user_time})

        return make_response({"ok": True})
        pass
